package com.example.klinedemo.carame

import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat

class H264Play(val width: Int, val height: Int) {

    var index = 0

    val mediaCodec: MediaCodec by lazy {
        MediaCodec.createEncoderByType("video/avc")
    }

    fun encode() {
        val mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height)
        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, width * height) // 比特率
        mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15) // 针率
        mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2) //I帧刷新时间

        mediaFormat.setInteger(
            MediaFormat.KEY_COLOR_FORMAT,
            MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible
        )// 输出格式
        mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
        mediaCodec.start()

    }

    fun start(bytes: ByteArray) {
        if (bytes.isEmpty()) return
        val inputBufferIndex = mediaCodec.dequeueInputBuffer(10000) ?: -1
        if (inputBufferIndex > 0) {
            val inputBuffer = mediaCodec.getInputBuffer(inputBufferIndex) ?: return
            inputBuffer.put(bytes)
            mediaCodec.queueInputBuffer(inputBufferIndex, 0, bytes.size, computPts(), 0)
            index++
        }

        // 开始输出
        val bufferInfo = MediaCodec.BufferInfo()
        val dequeueOutputBuffer = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000)
        if (dequeueOutputBuffer > 0) {
            val outputBuffer = mediaCodec.getOutputBuffer(dequeueOutputBuffer)
            mediaCodec.releaseOutputBuffer(dequeueOutputBuffer, false)
        }


    }

    fun computPts(): Long {
        return 1000000 / 15L * index
    }

}
